package space.jamestang.simpleci.server.handler

import io.ktor.server.application.Application
import io.ktor.server.routing.routing
import io.ktor.server.sse.sse
import kotlinx.coroutines.delay

fun Application.serverStatusHandler() {

    routing {
        sse("/status"){
            for (i in 1..10) {
                send(getSystemStatus())
                delay(5000)
            }
        }
    }
}

fun getSystemStatus(): String {

    val cpuLoad = Runtime.getRuntime().availableProcessors()
    val totalMemory = Runtime.getRuntime().totalMemory()
    val freeMemory = Runtime.getRuntime().freeMemory()
    val memUsage = (totalMemory - freeMemory) / totalMemory
    return """
        {
            "cpuLoad": $cpuLoad,
            "memory" : $memUsage
        }
    """.trimIndent()
}